package com.unohacha.qqj.fzdr.ui.activity.supply;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.LabelCategaryAdapter;
import com.unohacha.qqj.fzdr.adapter.imgpicker.FabricImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.CatData;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.LabelBean;
import com.unohacha.qqj.fzdr.bean.PublishTip;
import com.unohacha.qqj.fzdr.ui.activity.PubSettlementActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.GlideImgLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.MyGridView;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 纺织辅料
 */
public class ExcipientActivity extends BaseActivity implements FabricImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.ll_label)
    LinearLayout llLabel;
    @BindView(R.id.et_fault)
    EditText etFault;
    @BindView(R.id.et_number)
    EditText etNumber;

    @BindView(R.id.et_model)
    EditText etModel;

    @BindView(R.id.et_equip_time)
    EditText etEquipTime;
    @BindView(R.id.et_from)
    EditText etFrom;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.tv_label_count)
    TextView tvLabelCount;
    @BindView(R.id.gv_sing_style)
    MyGridView gridView;
    @BindView(R.id.et_extra)
    EditText etTxtra;
    LabelCategaryAdapter labelCategaryAdapter;

    private OptionsPickerView pvOptionsType;
    private String fabricName,fabricId;
    ArrayList<CatData.Two> listsDetial;
    ArrayList<String> listsCateName;
    ArrayList<LabelBean> listLabel;
    String type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_excipient;
    }

    List<CatData> listTwo;
    HashMap<String,String> map;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private FabricImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数
    private String sid;
    @Override
    protected void initView() {
        commonRightImage.setVisibility(View.INVISIBLE);

        map=new HashMap<>();
        fabricId=getIntent().getStringExtra("id");
        type=getIntent().getStringExtra("type");
        if(TextUtils.isEmpty(type))
            type = Prefer.getInstance().getKeyType();
        if ("1".equals(type))
            commonTitle.setText("辅料供应");
        else
            commonTitle.setText("辅料需求");
        listTwo=new ArrayList<>();
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new FabricImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                labelCategaryAdapter.chiceState(position);
                tvLabelCount.setText(labelCategaryAdapter.getSelectCount()+"个");
            }
        });

//        getPackerData();
        getLabelData();
        getTips();
    }

    @OnClick({R.id.ll_label, R.id.bt_next, R.id.common_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_label:
                break;
            case R.id.ll_select_num:
                break;
            case R.id.bt_next:
                if(etTitle.getText().length()==0){
                    ToastUtil.showCustomToast("请填写标题");
                    return;
                }
                String label=labelCategaryAdapter.getSelectList();
                if(label.length()<2){
                    ToastUtil.showCustomToast("请选择标签");
                    return;
                }
                String location=Prefer.obtainReLocation(ExcipientActivity.this);
                map.put("token",Prefer.getInstance().getToken());
                map.put("title",etTitle.getText().toString().trim());
                map.put("supply_cate_id",sid);
                map.put("typeid",type);
                map.put("spec",etNumber.getText().toString().trim());
                map.put("fabric_model","");
                map.put("material","");
                map.put("price_company",etFrom.getText().toString().trim());
                map.put("price",etEquipTime.getText().toString().trim());
                map.put("matching",label);
                map.put("content",etTxtra.getText().toString().trim());
                map.put("nums",etFault.getText().toString());
                map.put("nums_company",etModel.getText().toString().trim());

                mSubmit(map);
                break;
            case R.id.common_back:
                finish();
                break;
        }
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImgLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(ExcipientActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);

                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
        }
    }
    ArrayList<ImageItem> images = null;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }

    private void getPackerData(){
        String token=Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyCate")
                .addParam("token",token )
                .addParam("typeid","2")
                .request(new SimpleCallBack<BaseBean<List<CatData>>>() {
                    @Override
                    public void onSuccess(BaseBean<List<CatData>> data) {
                        if(data.getCode()==0){
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        listTwo.clear();
                        listTwo.addAll(data.getData());
                        for(int i=0;i<listTwo.size();i++){
                            if(listTwo.get(i).getId()==Integer.valueOf(fabricId)){
                                listsDetial=new ArrayList<>();
                                listsCateName=new ArrayList<>();
                                listsDetial.addAll(listTwo.get(i).getTwo());
                                for(int j=0;j<listTwo.get(i).getTwo().size();j++){
                                    listsCateName.add(listsDetial.get(j).getName());
                                }

                            }
                        }
                        sid=listsDetial.get(0).getId()+"";
                        pvOptionsType.setPicker(listsCateName);
                        hideLoading();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        hideLoading();
                    }
                });
    }

    private void getLabelData(){
        String token=Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyLabelMatching")
                .addParam("supply_cate_id",fabricId )
                .request(new SimpleCallBack<BaseBean<ArrayList<LabelBean>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<LabelBean>> data) {
                        if(data.getCode()==0){
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        listLabel=new ArrayList<>();
                        listLabel.addAll(data.getData());

                        labelCategaryAdapter=new LabelCategaryAdapter(ExcipientActivity.this,listLabel);
                        gridView.setAdapter(labelCategaryAdapter);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    private void getTips(){
        String token=Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyPrompt")
                .addParam("supply_cate_id",fabricId )
                .request(new SimpleCallBack<BaseBean<ArrayList<PublishTip>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<PublishTip>> data) {
                        if(data.getCode()==1){
                            for(int i=0;i<data.getData().size();i++){
//                                if(data.getData().get(i).getField_name().equals("数量单位")) {
//                                    numList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
//                                }else if(data.getData().get(i).getField_name().equals("扣幅单位")){
//                                    koufuList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
//                                }
                            }
                        }

                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }


    private void mSubmit(final HashMap<String,String> map){
        HashMap<String,String> parmas=new HashMap<>();
        parmas.put("token",Prefer.getInstance().getToken());
        parmas.put("type","1");
        UploadRequest uploadRequest= SuperHttp.upload("api/filepic/filePic");
        if(images!=null){
            for (int i=0;i<images.size();i++){
                uploadRequest.addImageFile("file"+i,new File(images.get(i).path));
            }
        }else {
            ToastUtil.showCustomToast("请选择图片");
//            map.put("list_pic","");
//            Intent intent=new Intent(ExcipientActivity.this, PubSettlementActivity.class);
//            intent.putExtra("params",map);
//            startActivity(intent);
            return;
        }

        uploadRequest.addParams(parmas);

        showLoading();
        uploadRequest.request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
            @Override
            public void onFail(int errCode, String errMsg) {
                ToastUtil.showCustomToast(errMsg);
                hideLoading();
            }

            @Override
            public void onSuccess(BaseBean<List<ImgBean>> data) {
                StringBuilder stringBuilder=new StringBuilder();
                for (int i=0;i<data.getData().size();i++){
                    stringBuilder.append(data.getData().get(i).getId()+",");
                }
                map.put("list_pic",stringBuilder.toString());
                Intent intent=new Intent(ExcipientActivity.this, PubSettlementActivity.class);
                intent.putExtra("params",map);
                startActivity(intent);

                hideLoading();
                finish();
            }
        });
    }
}
